#!/usr/bin/env python3
"""
Configuration Validator for Intelligent Rules V2.0
验证项目配置的完整性和正确性

Usage: python tools/config_validator.py
"""

import os
import sys
import yaml
import json
from pathlib import Path
from typing import Dict, List, Any, Optional

class ConfigValidator:
    """配置验证器"""
    
    def __init__(self, project_root: Optional[Path] = None):
        self.project_root = project_root or Path(__file__).parent.parent
        self.errors = []
        self.warnings = []
        self.info = []
        
    def validate_all_configs(self) -> Dict[str, Any]:
        """验证所有配置"""
        
        print("🔍 启动配置验证...")
        print("=" * 60)
        
        # 验证项目基础结构
        self._validate_project_structure()
        
        # 验证配置文件
        self._validate_config_files()
        
        # 验证环境配置
        self._validate_environment_configs()
        
        # 验证模块配置
        self._validate_module_configs()
        
        # 生成验证报告
        return self._generate_validation_report()
    
    def _validate_project_structure(self):
        """验证项目结构"""
        
        print("📁 验证项目结构...")
        
        required_dirs = [
            "foundation/core",
            "rules/core", "rules/system", "rules/evolution", "rules/validation",
            "coordination",
            "config/environments/development",
            "config/environments/production",
            "templates",
            "tools",
            "docs"
        ]
        
        for dir_path in required_dirs:
            full_path = self.project_root / dir_path
            if not full_path.exists():
                self.errors.append(f"缺少必需目录: {dir_path}")
            else:
                self.info.append(f"✅ {dir_path}")
        
        # 检查关键文件
        required_files = [
            "README.md",
            "requirements.txt",
            "config/project.yaml"
        ]
        
        for file_path in required_files:
            full_path = self.project_root / file_path
            if not full_path.exists():
                self.errors.append(f"缺少必需文件: {file_path}")
            else:
                self.info.append(f"✅ {file_path}")
    
    def _validate_config_files(self):
        """验证配置文件"""
        
        print("\n⚙️ 验证配置文件...")
        
        # 验证项目配置
        project_config = self.project_root / "config" / "project.yaml"
        if project_config.exists():
            try:
                with open(project_config, 'r', encoding='utf-8') as f:
                    config = yaml.safe_load(f)
                
                self._validate_project_config(config)
                self.info.append("✅ project.yaml 格式正确")
                
            except yaml.YAMLError as e:
                self.errors.append(f"project.yaml YAML格式错误: {str(e)}")
            except Exception as e:
                self.errors.append(f"读取project.yaml失败: {str(e)}")
        
        # 验证requirements.txt
        requirements_file = self.project_root / "requirements.txt"
        if requirements_file.exists():
            try:
                with open(requirements_file, 'r', encoding='utf-8') as f:
                    requirements = f.readlines()
                
                if len(requirements) > 0:
                    self.info.append(f"✅ requirements.txt ({len(requirements)} 个依赖)")
                else:
                    self.warnings.append("requirements.txt 为空")
                    
            except Exception as e:
                self.errors.append(f"读取requirements.txt失败: {str(e)}")
    
    def _validate_project_config(self, config: Dict[str, Any]):
        """验证项目配置内容"""
        
        # 检查必需字段
        required_fields = {
            "project": ["name", "version", "type"],
            "intelligent_rules": ["version", "integration_mode"]
        }
        
        for section, fields in required_fields.items():
            if section not in config:
                self.errors.append(f"project.yaml 缺少 {section} 部分")
                continue
                
            for field in fields:
                if field not in config[section]:
                    self.errors.append(f"project.yaml 缺少 {section}.{field}")
        
        # 验证项目类型
        if "project" in config and "type" in config["project"]:
            valid_types = ["web", "ai", "mobile", "enterprise", "custom"]
            project_type = config["project"]["type"]
            if project_type not in valid_types:
                self.warnings.append(f"未知的项目类型: {project_type}")
    
    def _validate_environment_configs(self):
        """验证环境配置"""
        
        print("\n🌍 验证环境配置...")
        
        environments = ["development", "production"]
        
        for env in environments:
            env_dir = self.project_root / "config" / "environments" / env
            if not env_dir.exists():
                self.errors.append(f"缺少环境配置目录: {env}")
                continue
            
            app_config = env_dir / "app.yaml"
            if app_config.exists():
                try:
                    with open(app_config, 'r', encoding='utf-8') as f:
                        config = yaml.safe_load(f)
                    
                    self._validate_environment_config(env, config)
                    self.info.append(f"✅ {env}/app.yaml")
                    
                except yaml.YAMLError as e:
                    self.errors.append(f"{env}/app.yaml YAML格式错误: {str(e)}")
                except Exception as e:
                    self.errors.append(f"读取{env}/app.yaml失败: {str(e)}")
            else:
                self.warnings.append(f"缺少 {env}/app.yaml")
    
    def _validate_environment_config(self, env: str, config: Dict[str, Any]):
        """验证单个环境配置"""
        
        # 检查环境标识
        if "environment" not in config:
            self.errors.append(f"{env}/app.yaml 缺少 environment 字段")
        elif config["environment"] != env:
            self.warnings.append(f"{env}/app.yaml environment 字段不匹配")
        
        # 检查关键配置段
        expected_sections = ["rules", "evolution", "logging", "performance"]
        for section in expected_sections:
            if section not in config:
                self.warnings.append(f"{env}/app.yaml 缺少 {section} 配置段")
    
    def _validate_module_configs(self):
        """验证模块配置"""
        
        print("\n📦 验证模块配置...")
        
        modules_dir = self.project_root / "modules"
        if not modules_dir.exists():
            self.errors.append("缺少 modules 目录")
            return
        
        # 检查模块目录
        expected_modules = ["ai_module", "web_module", "mobile_module", "enterprise_module"]
        
        for module in expected_modules:
            module_dir = modules_dir / module
            if module_dir.exists():
                readme_file = module_dir / "README.md"
                if readme_file.exists():
                    self.info.append(f"✅ {module} (有README)")
                else:
                    self.warnings.append(f"{module} 缺少README.md")
            else:
                self.warnings.append(f"缺少模块目录: {module}")
    
    def _generate_validation_report(self) -> Dict[str, Any]:
        """生成验证报告"""
        
        print("\n" + "=" * 60)
        print("📊 配置验证报告")
        print("=" * 60)
        
        # 显示错误
        if self.errors:
            print(f"\n❌ 错误 ({len(self.errors)}个):")
            for error in self.errors:
                print(f"  • {error}")
        
        # 显示警告
        if self.warnings:
            print(f"\n⚠️ 警告 ({len(self.warnings)}个):")
            for warning in self.warnings:
                print(f"  • {warning}")
        
        # 显示信息
        if self.info:
            print(f"\n✅ 验证通过 ({len(self.info)}个):")
            for info in self.info[:5]:  # 只显示前5个
                print(f"  • {info}")
            if len(self.info) > 5:
                print(f"  • ... 还有 {len(self.info) - 5} 项")
        
        # 总结
        total_checks = len(self.errors) + len(self.warnings) + len(self.info)
        success_rate = len(self.info) / total_checks * 100 if total_checks > 0 else 0
        
        print(f"\n📈 验证总结:")
        print(f"  总检查项: {total_checks}")
        print(f"  成功率: {success_rate:.1f}%")
        
        if len(self.errors) == 0:
            print(f"  状态: ✅ 配置基本正确")
        else:
            print(f"  状态: ❌ 存在 {len(self.errors)} 个严重问题")
        
        return {
            "total_checks": total_checks,
            "success_rate": success_rate,
            "errors": self.errors,
            "warnings": self.warnings,
            "info": self.info,
            "status": "valid" if len(self.errors) == 0 else "invalid"
        }

def main():
    """主程序"""
    print("🔧 Intelligent Rules V2.0 配置验证器")
    print("验证项目配置的完整性和正确性")
    print()
    
    validator = ConfigValidator()
    result = validator.validate_all_configs()
    
    # 退出码
    exit_code = 0 if result["status"] == "valid" else 1
    
    print(f"\n🎯 配置验证完成，退出码: {exit_code}")
    sys.exit(exit_code)

if __name__ == "__main__":
    main() 